import { Component, OnInit, ViewChild, OnDestroy, ViewChildren, QueryList } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DatePipe } from "@angular/common";
import { Http } from "@angular/http";
import { Observable } from "rxjs/Rx";
import { Subject } from "rxjs/Subject";
import { List } from 'linqts';
import { Farm } from "../../../entity/farm.model";
import { Device } from "../../../entity/device.model";
import { TurbStatus } from "../../../entity/turbstatus.model";
import { Model } from "../../../entity/model.model";
import { ModelParam } from "../../../entity/model-Param";
import { Tag } from "../../../entity/tag.model";
import { TagData } from "../../../entity/tag-data.model";
import { InverterStatus } from "./inverterStatus.model";
import { TurbComponent } from "../../../entity/turbcomponent.model"

//服务
import { DataSourceService } from "../../../service/data-source/data-source.service";
import { ApplicationService } from "../../../service/application.service";
import { ModelService } from "../../../service/model.service";
import { ModelParamService } from "../../../service/model-param.service";
import { TurbStatusService } from "../../../service/turbstatus.service";
import { NzMessageService } from 'ng-zorro-antd';
import { InterceptorService } from '../../../service/interceptor/interceptor-service';

//报警模块
import { InverterAlarmListComponent } from "./inverter-alarm-list/inverter-alarm-list.component";
import { TurbcomponentService } from "../../../service/turbcomponent.service";
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';

@Component({
	selector: 'app-inverter-detail',
	templateUrl: './inverter-detail.component.html',
	styleUrls: ['./inverter-detail.component.css']
})
export class InverterDetailComponent implements OnInit {

	@ViewChild(InverterAlarmListComponent)
	AlarmList: InverterAlarmListComponent;
	public farmCategory: FarmCategoryEnum = FarmCategoryEnum.photovoltaic;
	public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.inverter];

	/**
	 * 数据源服务
	 * 
	 * @private
	 * @type {DataSourceService}
	 * @memberof InverterDetailComponent
	 */
	private dataSource: DataSourceService;

	/**
   * 路由型号Id和deviceId  
   * 
   * @type {DeviceId}@memberof InverterDetailComponent
   */
	public deviceId: number;
	public farmId: number;

	/**
	* 当前风场风机（逆变器）
	* 
	* @type {Device}@memberof InverterDetailComponent
	*/
	// tslint:disable-next-line:indent
	public currentInverter: Device;

	/**
	* 逆变器状态集合
	* 
	* @type {TurbStatus}@memberof InverterDetailComponent
	*/
	// tslint:disable-next-line:indent
	private inverterStatus: TurbStatus[];

	/**
	* 设备当前状态
	* 
	* @type {TurbStatus}@memberof InverterDetailComponent
	*/
	public currentStatus: TurbStatus;

	/**
	* 设备历史状态
	* 
	* @type {InverterStatus}@memberof InverterDetailComponent
	*/
	public inverterStatuses: InverterStatus[] = [];

	/**
	  * 型号参数集合
	  * 
	  * @type {ModelParam}@memberof InverterDetailComponent
	  */
	public modelParams: ModelParam[] = [];
	public model: Model;
	public models: Model[] = [];

	/**
	  * 当前设备型号参数
	  * 
	  * @type {ModelParam}@memberof InverterDetailComponent
	  */
	private currentModelParam: ModelParam[];

	/**
	  * 当前用户风场
	  * 
	  * @type {Farm}@memberof InverterDetailComponent
	  */
	private farms: Farm[];

	/**
	 * 当前风机的测点信息
	 * 
	 * @type {Tag}@memberof InverterDetailComponent
	 */
	private tags: Tag[];

	/**
	 * 是否显示风机选择组件（设备）
	* 
	* @type {boolean}@memberof InverterDetailComponent
	*/
	public showSelector: boolean = false;

	/**
	 * 滑过的风机系统
	* 
	* @type {any}@memberof TurbineDetailComponent
	*/
	private n: any;

	/**
	 * 逆变器基本信息数据
	 * 
	 * @type {TagData[]}@memberof InverterDetailComponent
	 */
	public basicData: TagData[] = [];
	public total: TurbineDetail[] = [];
	private isShow: boolean = false;
	// 基本信息点
	private basicInfoCode: number = 15;
	private timer: any = null;

	private curWwwPath: string;
	private pathName: string;
	private pos: number;
	public localhostPath: string;

	// 逆变器系统对应图片
	private turbineCImage: TurbineCImage[] = [
		{
			valueCode: 14, // 其他系统
			images: ["categorize3.png", "InverterBg.png", "categorize.png", "categorize2.png"],
		},
		{
			valueCode: 18, // 箱变系统
			images: ["packaged2.png", "packaged.png", "packaged4.png", "packaged3.png"],
		},
		{
			valueCode: 519, // 逆变器系统
			images: ["InverterBg.png", "InverterBg.png", "Inverter1.png", "Inverter1.png"],
		}
	]
	private turbineComponents: TurbComponent[];
	/**
  * 开关量为1时颜色
  * 
  * @type {string}
  * @memberof InverterDetailComponent
  */
	switchingValue1 = '#008000';
	/**
	 * 开关量为0时颜色
	 * 
	 * @type {string}
	 * @memberof InverterDetailComponent
	 */
	switchingValue2 = '#FFFF00';
	constructor(
		private http: InterceptorService,
		private datePipe: DatePipe,
		private application: ApplicationService,
		private modelService: ModelService,
		private TurbStatusService: TurbStatusService,
		private modelParamService: ModelParamService,
		private router: Router,
		private activatedRoute: ActivatedRoute,
		private turbcompService: TurbcomponentService,
		private _message: NzMessageService
	) {

	}

	ngOnInit() {

		if (this.application.currentApplicationParams && this.application.currentApplicationParams['switchingValue1']) {
			this.switchingValue1 = this.application.currentApplicationParams['switchingValue1'].paramValue;
		}
		if (this.application.currentApplicationParams && this.application.currentApplicationParams['switchingValue2']) {
			this.switchingValue2 = this.application.currentApplicationParams['switchingValue2'].paramValue;
		}
		this.curWwwPath = window.location.href;
		this.pathName = window.location.pathname;
		this.pos = this.curWwwPath.indexOf(this.pathName);
		this.localhostPath = this.curWwwPath.substring(0, this.pos);
		if (this.localhostPath.indexOf("localhost") < 0) {
			this.localhostPath = this.localhostPath + '/dist'
		}
		this.activatedRoute.params.subscribe((params:  { farmId: number, deviceId: number }) => {
			if (params.deviceId != 0) {
				this.deviceId = params.deviceId;
			}
			if (params.farmId != 0) {
				this.farmId = params.farmId;
			}
		});



		

		let turbStatus = this.TurbStatusService.getInverterStatus();
		let turbComs = this.turbcompService.getTurbComponents();
		Promise.all([turbStatus, turbComs])
			.then(res => {
				if (res[0]) {
					this.inverterStatus = [...res[0]];
				};
				if (res[1]) {
					this.turbineComponents = [...res[1].filter(o => o.parentId === 0 || o.parentId == null)];
				};
				this.setCurrentStatus();
			})
			.catch(err => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('数据初始化失败，' + err, { nzDuration: 3000 });
				}

				//console.log(err)
			})

	}

	public ngOnDestroy(): void {
		if (this.dataSource != null)
			this.dataSource.dispose();
	}

	private setCurrentStatus() {
		if (!this.currentStatus) {
			this.currentStatus = this.inverterStatus.find(o => o.statusValue === 1);
		}
	}

	/**
	 * 滑风机图圆点部分时显示对应风机系统
	* 
	* @type {}@memberof InverterDetailComponent
	*/
	public onMouseTitleEnter(index: number, img: Images) {
		if (img && img.icon) {
			let image: string = img.icon;
			img.icon = img.iconHover;
			img.iconHover = image;
		}

		clearTimeout(this.timer);
		this.timer = setTimeout(() => {
			this.n = index;
		}, 300)
		return false;
	}
	/**
	* 滑出风机图圆点部分时隐藏对应风机系统
	* 
	* @type {}@memberof InverterDetailComponent
	*/
	public onMouseTitleLeave(index: number, img: Images) {
		clearTimeout(this.timer);
		setTimeout(() => {
			if (img && img.icon) {
				let image: string = img.icon;
				img.icon = img.iconHover;
				img.iconHover = image;
			}
			this.n = false;
		}, 300)

		return false;
	}

	/**
	 * 得到风机型号信息
	* 
	* @type {}@memberof InverterDetailComponent
	*/
	getInverterModelParma() {
	
		this.currentModelParam = this.modelParams ? this.modelParams.filter(o => this.currentInverter && (o.modelId == this.currentInverter.modelId)) : [];
		this.modelService.getTagByModelId(this.currentInverter.modelId)
			.then(res => {
				// tslint:disable-next-line:indent
				if (res) {
					this.tags = [...res];
					this.getInverterCode();
				}

			})
			.catch(err => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('测点数据' + err, { nzDuration: 3000 });
				}

				//console.log(err);
			})
	}

	getInverterCode() {
	
		this.AlarmList.upData([this.currentInverter.deviceId], new Date(this.datePipe.transform(new Date(), "yyyy-MM-dd")), new Date());
		this.basicData = [];
		this.total = [];
		let tagDatas: TagData[] = [];

		//注销数据源
		if (this.dataSource != null) {
			this.dataSource.dispose();
		}
		if (this.currentInverter == null)
			return;

		let farmCode = this.currentInverter.farmCode;
		let deviceCode = this.currentInverter.deviceCode;

		this.dataSource = new DataSourceService(this.http, this.datePipe);
		// 创建该逆变器的测点
		this.tags.forEach(tag => {
			// 绑定数据
			let tagData: TagData = this.dataSource.binding([farmCode, deviceCode], tag);
			tagData.tagName = tag.tagName;
			tagData.tagUnit = tag.tagUnit ? "(" + tag.tagUnit + ")" : tag.tagUnit;
			tagData.turbComponent = tag.turbComponentId;
			tagData.tagKind = tag.tagKind;
			tagDatas.push(tagData);
		});
		if (!this.turbineComponents) return false;

		// 创建该逆变器部件以及部件下的测点
		this.turbineComponents.forEach((component, index) => {
			if (component.turbComponentId !== this.basicInfoCode) {
				let img: Images;
				let i = this.turbineCImage.findIndex(o => o.valueCode == component.turbComponentId);
				if (i > -1) {
					img = {
						icon: this.turbineCImage[i].images[2],
						iconHover: this.turbineCImage[i].images[3],
						titleImage: this.turbineCImage[i].images[0],
						bgImage: this.turbineCImage[i].images[1],
					}
					this.total.push({
						title: component.turbComponentName,
						valueCode: component.turbComponentId,
						data: tagDatas.filter(o => o.turbComponent == component.turbComponentId),
						img: img,
					});
				} else {
					this.total.push({
						title: component.turbComponentName,
						valueCode: component.turbComponentId,
						data: tagDatas.filter(o => o.turbComponent == component.turbComponentId),
						img: img,
					});
				}
			} else {
				this.basicData = tagDatas.filter(o => o.turbComponent == component.turbComponentId);
			}
		});
		const interverStatus = this.application.tagDict["TurbineStatus"];
		// 开始订阅数据
		this.dataSource
			.begin()
			.subscribe(
				next => {
					try {
						let tagData = next.find(o => o.code.endsWith(interverStatus.tagCode));  // 逆变器状态
						if (tagData != null) {
							// 设置当前状态
							let i = this.inverterStatus.findIndex(o => o.statusValue == tagData.value);
							if (i >= 0)
								this.currentStatus = this.inverterStatus[i];
						}
					} catch (error) {
						console.log(error)
					}
				},
				error => {
					console.log("app-inverter-detail has error", error);
				});

		// 设备状态（逆变器状态）
		
		let start1 = new Date(this.datePipe.transform(new Date(), "yyyy/MM/dd"));
		let end1 = new Date();

		// 风机状态点
		let statusCode = this.dataSource.buildTagCode([this.currentInverter.farmCode, this.currentInverter.deviceCode], interverStatus);
		this.dataSource
			.history
			.getDeviceStatuses([statusCode], start1, end1)
			.then(res => {
				//try {
				res.sort(function (a, b) {
					return new Date(b.time).getTime() - new Date(a.time).getTime();
				});
				this.inverterStatuses = [];
				res.forEach((v, i) => {
					let index = this.inverterStatus.findIndex(o => o.statusValue == v.value);
					if (index >= 0) {
						this.inverterStatuses.push(
							{
								statusName: this.inverterStatus[index].statusName,
								statusValue: v.value,
								time: v.time,
							}
						)
					} else {
						this.inverterStatuses.push({
							statusName: this.inverterStatus[0].statusName,
							statusValue: v.value,
							time: v.time,
						});
					}
				});
				/* } catch (error) {
					console.log(error);
				} */
			})
			.catch(error => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('风机状态' + error, { nzDuration: 3000 });
				}

				//console.log("app-inverter-detail has error", error);
			});

	}

	getModelParams() {
	
		const modelGet = this.modelService.getModelWithFactory();
		const modelParamGet = this.modelParamService.getModelParamsByModeID(this.currentInverter.modelId);
		Promise.all([modelGet, modelParamGet])
			.then(res => {
				this.models = [...res[0]];
				let index = this.models.findIndex(o => o.modelId == this.currentInverter.modelId);
				if (index >= 0) {
					this.model = this.models[index];
				} else {
					this.model = null;
				}
				if (res[1].length > 0) {
					this.modelParams = res[1];
				} else {
					this.modelParams = [];
				}
			})
			.catch(err => {
				if (this.application.appConfigData.isShowErr) {
					this._message.info('型号参数数据' + err, { nzDuration: 3000 });
				}

				//console.log(err)
			})

	}
	onSelectFarmRadio(ev: Device[]) {
// 		console.log(ev)
// debugger
		this.currentInverter = ev[0];
		if (!this.currentInverter.deviceId) return false;
		this.getModelParams();
		this.getInverterModelParma();
		this.showSelector = false;
	}

	/**
	* 滑出风机系统tab时隐藏对应的风机系统
	* 
	* @type {}@memberof InverterDetailComponent
	*/
	public onMouseLeave(ev) {
		if (!ev.toElement) return false;
		this.showSelector = false;
	}
	/**
	 * 滑入风机系统tab时显示对应的风机系统
	 * 
	 * @type {}@memberof InverterDetailComponent
	 */
	public onMouseEnter() {
		this.showSelector = true;
	}

}

interface TurbineDetail {
	title: string;
	valueCode: number;
	data?: TagData[];
	img?: Images;
}
interface Images {
	icon?: string;
	iconHover?: string;
	titleImage?: string;
	bgImage?: string;
}
interface TurbineCImage {
	valueCode: number;
	images: string[];
}



// WEBPACK FOOTER //
// ./src/app/module/monitor/inverter-detail/inverter-detail.component.ts